/**
 * <b>项目名：</b>亲子分享-服务端项目<br/>
 * <b>包名：</b>com.saas.service<br/>
 * <b>文件名：</b>AuthorizationService.java<br/>
 * <b>版本信息：</b>V1.0<br/>
 * <b>日期：</b>2014-9-20-下午12:51:51<br/>
 * <b>作者：</b><br/>
 * <b>Copyright (c)</b> 2014坚果(北京)科技有限公司-版权所有<br/>
 */
package com.saas.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.crypto.Data;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.saas.dao.MongoDAO;
import com.saas.exception.ServiceException;
import com.saas.service.saas.UserService;
import com.saas.util.APPUtils;
import com.saas.util.Constant;
import com.saas.util.DataUtils;
import com.saas.util.DateUtils;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

 /**
 *
 * <b>类名称：</b>AuthorizationService<br/>
 * <b>类描述：</b>认证服务<br/>
 * <b>创建人：</b><br/>
 * <b>修改人：</b><br/>
 * <b>修改时间：</b>2014-9-20 下午12:51:51<br/>
 * <b>修改备注：</b><br/>
 * @version 1.0.0<br/>
 *
 */
@Component
public class AuthorizationService {
	
	protected static Logger logger = LoggerFactory.getLogger(AuthorizationService.class);
	
	@Autowired
	private MongoDAO mongoDao;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 
	 * auth(ApI调用认证)
	 * 
	 * @param model
	 * @param json {objectId:{userObjectId},sessionToken:{sessionToken}}
	 * @return
	 * @throws Exception
	 *             boolean
	 * @exception
	 * @since 1.0.0
	 */
	public boolean auth(String model, JSONObject userObject) throws ServiceException {
//		JSONObject userObject = com.alibaba.fastjson.JSON.parseObject(json);
		String user = mongoDao.get(model, userObject.getString(Constant.OBJECTID));
		JSONObject dbUserObject = com.alibaba.fastjson.JSON.parseObject(user);
		logger.info("userObject:"+userObject);
		logger.info("dbUserObject:"+user);
		
		JSONObject tokens = dbUserObject.getJSONObject(Constant.user_tokens);
		String u1_sessionToken = "";
		if (DataUtils.isNotEmpty(tokens)) {
			JSONObject siteToken = tokens.getJSONObject(APPUtils.getTokenSite(userObject.getString(Constant.user_site)));
			if (DataUtils.isNotEmpty(siteToken)) {
				u1_sessionToken = siteToken.getString(Constant.user_sessionToken);
			}
		}
		String u2_sessionToken = userObject.getString(Constant.user_sessionToken);
		if (u2_sessionToken.equals(u1_sessionToken)) {
			return true;
		}
		return false;
	}

	/**
	 * login(用户登录,成功后返回用户信息)
	 * 
	 * @param model
	 * @param id
	 * @return boolean
	 * @exception
	 * @since 1.0.0
	 */
	public JSONObject login(String model, String json) throws Exception {
		JSONObject response = null;
		JSONObject loginUser = JSON.parseObject(json);
		DBObject user = null;
		if(StringUtils.isNotBlank(loginUser.getString("verifycode"))){//手机验证码登陆
			boolean verify = userService.verifyCode(loginUser.getString("loginIdentifying"), loginUser.getString("verifycode"));
			if(verify){
				user = userService.findUserByMobilePhoneNumber(model,loginUser.getString("loginIdentifying"));
			}
		}else{//用户名密码登陆
			user = mongoDao.login(model, json);
		}
		
		if (user != null) {
			DBObject update = new BasicDBObject();// 设置更新内容
			//注释掉原有的token存储更新
//			update.put(Constant.user_sessionToken, APPUtils.generateAccessToken());// 生成sessionToken
//			update.put(Constant.user_secretKey, APPUtils.generateSecretKey((String) user.get(Constant.user_username)));// 用户分配密钥
			
			//新token存储方式-sid
			//1.获取已有tokens
			DBObject tokens = (DBObject) user.get(Constant.user_tokens);
			if (!DataUtils.isNotEmpty(tokens)) {
				tokens = new BasicDBObject();
			}
			//2.根据来源更新tokens
			String  site = (String) loginUser.get(Constant.user_site);
			DBObject token = new BasicDBObject();
			token.put(Constant.user_sessionToken, APPUtils.generateAccessToken());// 生成sessionToken
			token.put(Constant.user_secretKey, APPUtils.generateSecretKey((String) user.get(Constant.user_username)));// 用户分配密钥
			tokens.put(APPUtils.getTokenSite(site), token);
			//3.更新其对应的token
			update.put(Constant.user_tokens, tokens);
			
			//更新用户当前使用版本
			String currentVersion = loginUser.getString(Constant.user_currentVersion);
			String lastVersion = "";
			if(user.containsField(Constant.user_currentVersion)){
				lastVersion = user.get(Constant.user_currentVersion).toString();
			}
			if(StringUtils.isNoneBlank(currentVersion) 
					&& !currentVersion.equalsIgnoreCase(lastVersion) //当前版本有并且有上一个版本
					|| StringUtils.isBlank(lastVersion)&&StringUtils.isNoneBlank(currentVersion)//之前没有版本信息，当前需要更新
					){
				update.put(Constant.user_currentVersion, loginUser.getString(Constant.user_currentVersion));
			}
			update.put(Constant.user_lastLoginTime, DateUtils.date24ToString(new Date()));
			mongoDao.update(model, update.toString(), (String)user.get(Constant.OBJECTID));
			user.put(Constant.user_tokens, tokens);
			user.put(Constant.user_sessionToken, token.get(Constant.user_sessionToken));
			user.put(Constant.user_secretKey, token.get(Constant.user_secretKey));
			user.removeField("_id");
			user.removeField("password");
			user.removeField("salt");
			response  = JSON.parseObject(user.toString());
		}
		return response;
	}
}
